/**
 * 权限管理组合式函数
 */

import { computed } from 'vue'
import { useUserStore } from '@/stores/user'

export function usePermission() {
  const userStore = useUserStore()

  // 权限映射表
  const rolePermissions = {
    admin: ['*'], // 超级管理员拥有所有权限
    editor: [
      'user:view',
      'user:create',
      'user:edit',
      'content:view',
      'content:create',
      'content:edit',
      'order:view'
    ],
    normal: [
      'user:view',
      'content:view',
      'order:view'
    ],
    viewer: [
      'user:view',
      'content:view'
    ]
  }

  // 获取用户权限列表
  const userPermissions = computed(() => {
    const userRoles = userStore.userRoles
    const permissions = []
    
    userRoles.forEach(role => {
      const rolePerms = rolePermissions[role] || []
      permissions.push(...rolePerms)
    })
    
    return [...new Set(permissions)] // 去重
  })

  // 检查是否有指定权限
  const hasPermission = (permission) => {
    if (!permission) return true
    
    const permissions = userPermissions.value
    
    // 如果有通配符权限，返回 true
    if (permissions.includes('*')) {
      return true
    }
    
    // 检查单个权限
    if (typeof permission === 'string') {
      return permissions.includes(permission)
    }
    
    // 检查权限数组（需要拥有所有权限）
    if (Array.isArray(permission)) {
      return permission.every(p => permissions.includes(p))
    }
    
    return false
  }

  // 检查是否有任意一个权限
  const hasAnyPermission = (permissions) => {
    if (!Array.isArray(permissions)) {
      return false
    }
    
    return permissions.some(permission => hasPermission(permission))
  }

  // 检查是否有指定角色
  const hasRole = (role) => {
    const userRoles = userStore.userRoles
    
    if (typeof role === 'string') {
      return userRoles.includes(role)
    }
    
    if (Array.isArray(role)) {
      return role.some(r => userRoles.includes(r))
    }
    
    return false
  }

  // 检查是否是管理员
  const isAdmin = computed(() => {
    return userStore.userRoles.includes('admin')
  })

  return {
    userPermissions,
    hasPermission,
    hasAnyPermission,
    hasRole,
    isAdmin
  }
}
